package com.hivekion.common.security;

import com.hivekion.system.domain.SysUser;
import com.hivekion.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;


/*
 * 登录失败监听
 *
 * */
@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    @Autowired
    private ISysUserService userService;

    @Value("${user.default.failsCount}")
    private Integer failsCount;

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
        String account = authenticationFailureBadCredentialsEvent.getAuthentication().getPrincipal().toString();
        SysUser user = userService.getUserByUserName(account);
        if (user != null) {
            Integer fails = user.getFails();
            if (failsCount >= fails) {
                user.setFails(fails++);
                userService.saveOrUpdate(user);        // 更新失败次数
            } else {
                user.setStatus(1);
                userService.saveOrUpdate(user);        // 停用账户
            }
        }
    }
}
